package com.permission_server.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.permission_server.entity.SysPermissionEntity;
import com.permission_server.entity.SysUserEntity;
import com.permission_server.service.SysPermissionService;
import com.permission_server.service.SysUserService;
import com.permission_server.util.responseUtil.ResponseEnum;
import com.permission_server.util.responseUtil.ResponseUtil;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Date;

@RestController
@RequestMapping("/menu")
@Api(tags = "菜单管理接口")
public class MenuController {

    @Autowired
    SysPermissionService sysPermissionService;

    @Autowired
    SysUserService sysUserService;


    @GetMapping("/pullAllMenuPermission")
    public ResponseUtil pullAllMenuPermission() {
        return ResponseUtil.setE(ResponseEnum.OK).setData(sysPermissionService.list());
    }

    @PostMapping("/updateMenuPermission")
    public ResponseUtil updateMenuPermission(@RequestBody SysPermissionEntity sysPermission) {
        if (ObjectUtil.isEmpty(sysPermission)) ResponseUtil.setE(ResponseEnum.PARAMS_ERROR);
        SysUserEntity sysUserEntity = LoginController.getCurrentLoginUserInfo();
        if (StrUtil.isEmpty(sysPermission.getId())) {
            sysPermission.setCreateBy(sysUserEntity.getUsername());
            sysPermission.setCreateTime(new Date());
            sysPermission.setUpdateBy(sysUserEntity.getUsername());
            sysPermission.setUpdateTime(new Date());
        } else {
            sysPermission.setUpdateBy(sysUserEntity.getUsername());
            sysPermission.setUpdateTime(new Date());
        }
        if (sysPermissionService.saveOrUpdate(sysPermission))
            return ResponseUtil.setE(ResponseEnum.OK).setMsg("菜单权限【" + sysPermission.getName() + "】更新成功");
        return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("菜单权限【" + sysPermission.getName() + "】更新失败");
    }

    @PostMapping("/delMenuPermission")
    public ResponseUtil delMenuPermission(@RequestBody String[] idList) {
        boolean remove = sysPermissionService.removeByIds(Arrays.asList(idList));
        if (remove) return ResponseUtil.setE(ResponseEnum.OK).setMsg("【" + idList.length + "】个菜单权限删除成功");
        return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("菜单权限删除失败");
    }
}
